'use strict';

// 该文件尝试删除 get _routes()

const koaRouter = require('koa-router');
const join = require('path').join;
const run = require('./run');
const methods = require('methods').concat('all');

module.exports = class Router {
  constructor (configure) {
    this._routes = []
    methods.forEach(method => {
      const self = this;
      this[method] = function (path, actionAndoptions) {
        actionAndoptions = Array.from(arguments).slice(1);
        self[method][path] = [].concat(actionAndoptions);
        self._routes.push([method, path, ...actionAndoptions])
      };
    });
    this.use = (path, subRouter) => {
      if (typeof subRouter === 'function') {
        const sub = new Router(subRouter);
        sub._routes.forEach(item => this._routes.push([item[0], path + item[1], ...item.slice(2)]))
      } else {
        this.use[path] = subRouter;
      }
    };
    if (typeof configure === 'function') {
      configure(this);
    }
  }

  forKoa() {
    const router = new koaRouter();
    const routes = this._routes;
    routes.forEach(route => {
      const method = route[0];
      const path = route[1];
      const actionsAndOptions = route.slice(2);
      const middlewares = actionsAndOptions.filter(i => typeof i === 'function');
      const options = middlewares.length < actionsAndOptions.length ? actionsAndOptions[middlewares.length] : null;
      const controller = middlewares.pop();
      // 这里的middlewares是一个数组，要想执行到run，需要每个middlewares函数最后执行next()
      // 对于后台，可能不只有run这一个中间件，对于特殊的接口，可能业务需要经过多个中间件的判断，就体现了middlewares的重要了
      //  如果中间件比较多的话，也是需要分目录，const pictureMiddleware = require(middlewares/picture)
      // 不多的话，只写在一个叫middlewares.js的文件里也可以
      // 那么在路由中就写成了 router.post('/api/picture/upload', middlewares.checkSize, picture.upload, {
      // shouldLogin: true
      // })
      router[method].apply(router, [].concat(path, middlewares, run(controller, options)));
      // router[method](path,run(action, options));
    });
    return router;
  }
};
